﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Macds.Core.XML.Excel
{
    public class ExcelApplication
    {
        public ExcelWorksheetCollection Worksheets { get; set; }
        public string FilePath { get; set; }

        public ExcelApplication()
        {
            this.Worksheets = new ExcelWorksheetCollection();
        }

        public override string ToString()
        {
            StringBuilder content = new StringBuilder();
            content.Append("<?xml version=\"1.0\"?>\r\n");
            content.Append("<?mso-application progid=\"Excel.Sheet\"?>");

            string workbook = "<Workbook ";
            workbook += "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
            workbook += "xmlns:o=\"urn:schemas-microsoft-com:office:office\" ";
            workbook += "xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ";
            workbook += "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
            workbook += "xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n";

            string properties = "<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n";
            properties += "<Author>DataSafe Corporate System v1.0</Author>\r\n";
            properties += "<LastAuthor>ExcelApplication Class</LastAuthor>\r\n";
            properties += "<Created>" + DateTime.Now.ToLongDateString() + "T" + DateTime.Now.ToLongTimeString() + "Z</Created>\r\n";
            properties += "<Company>DataSafe</Company>\r\n";
            properties += "<Version>1.00</Version>\r\n";
            properties += "</DocumentProperties>\r\n";
            properties += "<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n";
            properties += "<WindowHeight>6795</WindowHeight>\r\n";
            properties += "<WindowWidth>8460</WindowWidth>\r\n";
            properties += "<WindowTopX>120</WindowTopX>\r\n";
            properties += "<WindowTopY>15</WindowTopY>\r\n";
            properties += "<ProtectStructure>False</ProtectStructure>\r\n";
            properties += "<ProtectWindows>False</ProtectWindows>\r\n";
            properties += "</ExcelWorkbook>\r\n";

            content.Append(workbook);
            content.Append(properties);

            foreach (ExcelWorksheet w in Worksheets)
            {
                content.Append(w.ToString());
            }

            content.Append("</ss:Workbook>");
            return content.ToString();
        }

        public bool SaveFile(string path)
        {
            this.FilePath = path;
            return SaveFile();
        }

        public bool SaveFile()
        {
            bool status = false;

            if (this.FilePath == null || this.FilePath == "")
            {
                throw new NullReferenceException("The FilePath is empty");
            }

            string path = this.FilePath;
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine(this.ToString());
                status = true;
            }

            return status;
        }

        public byte[] CreateExcelInBytes()
        {
            byte[] buffer = null;

            string path = "";

            if (this.FilePath == null || this.FilePath == "")
            {
                path = "C:\\" + Guid.NewGuid().ToString() + ".xls";
            }
            else
            {
                path = this.FilePath;
            }

            if (SaveFile(path))
            {
                try
                {
                    FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);

                    try
                    {
                        int length = (int)fileStream.Length;
                        buffer = new byte[length];
                        int count;
                        int sum = 0;

                        while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                            sum += count;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        fileStream.Close();
                        File.Delete(path);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            return buffer;
        }
    }
}
